package repository

import (
	"github.com/jinzhu/gorm"
	"mall-go/common"
	"mall-go/dto"
	"mall-go/model"
	"mall-go/util"
	"mall-go/vo"
	"strings"
	"time"
)

type ShoppingCartRepo struct {
	DB *gorm.DB
}

func NewShoppingCartRepo() ShoppingCartRepo {
	db := common.GetDB()
	return ShoppingCartRepo{DB: db}
}

func (receiver ShoppingCartRepo) GetCartItemsForSettle(cartItemIds string, userId uint) []vo.NewBeeMallShoppingCartItemVO {
	if len(cartItemIds) == 0 {
		panic("购物项不能为空")
	}
	//根据用户id和购物项id集合查询数据
	var newBeeMallShoppingCartItems []model.ShoppingCart
	receiver.DB.Where("cart_item_id in ("+cartItemIds+")").Where("user_id = ? and is_deleted = 0", userId).Find(&newBeeMallShoppingCartItems)
	if len(newBeeMallShoppingCartItems) == 0 {
		panic("购物项不能为空")
	}

	if len(newBeeMallShoppingCartItems) != len(strings.Split(cartItemIds, ",")) {
		panic("参数异常")
	}
	return receiver.getNewBeeMallShoppingCartItemVOS(newBeeMallShoppingCartItems)
}

func (receiver ShoppingCartRepo) GetMyShoppingCartItems(cartDTO dto.ShopCartPageDTO) vo.CartPageResult {
	newBeeMallShoppingCartItems := receiver.findMyNewBeeMallCartItems(cartDTO)
	//查询总数
	var total int
	receiver.DB.Model(&model.ShoppingCart{}).Where("user_id = ? and is_deleted = 0", cartDTO.UserId).Count(&total)
	//处理字符串过长问题并做数据转换
	list := receiver.getNewBeeMallShoppingCartItemVOS(newBeeMallShoppingCartItems)

	return vo.CartPageResult{
		List: list,
		PageResult: vo.PageResult{
			TotalCount: total,
			PageSize:   cartDTO.Page,
			CurrPage:   cartDTO.Limit,
			TotalPage:  total / cartDTO.Page,
		},
	}
}

// GetMyShoppingCartItemsByUserId 根据id获取购物车数据
func (receiver ShoppingCartRepo) GetMyShoppingCartItemsByUserId(userId int) []vo.NewBeeMallShoppingCartItemVO {
	var shoppingCartItems []model.ShoppingCart
	receiver.DB.Where("user_id = ? and is_deleted = 0", userId).Limit(20).Find(&shoppingCartItems)
	return receiver.getNewBeeMallShoppingCartItemVOS(shoppingCartItems)
}

// GetNewBeeMallCartItemById 根据购物车id查询购物车信息
func (receiver ShoppingCartRepo) GetNewBeeMallCartItemById(newBeeMallShoppingCartItemId int) model.ShoppingCart {
	var newBeeMallShoppingCartItem model.ShoppingCart
	receiver.DB.Where("where cart_item_id = ? and is_deleted = 0", newBeeMallShoppingCartItemId).First(newBeeMallShoppingCartItem)
	return newBeeMallShoppingCartItem
}

func (receiver ShoppingCartRepo) DeleteById(newBeeMallShoppingCartItemId int, userId uint) bool {
	itemById := receiver.GetNewBeeMallCartItemById(newBeeMallShoppingCartItemId)
	if itemById.CartItemId == 0 {
		return false
	}
	//检验用户id是否一致
	if userId != itemById.UserId {
		return false
	}
	//执行删除操作
	if err := receiver.DB.Model(&itemById).Update("is_deleted = 1").Error; err != nil {
		return false
	}
	return true
}

func (receiver ShoppingCartRepo) SaveNewBeeMallCartItem(cartRequest dto.CartRequest, userId int) string {
	//根据用户id和商品id查询购物车数据
	var temp model.ShoppingCart
	receiver.DB.Where("user_id = ? and goods_id = ? and is_deleted = 0", userId, cartRequest.GoodsId).First(&temp)
	if temp.CartItemId != 0 {
		//已经存在
		panic("已存在无需重复添加")
	}
	goodsRepo := NewMallGoodsRepo()
	goodsInfo := goodsRepo.GetNewBeeMallGoodsById(cartRequest.GoodsId)
	//商品为空
	if goodsInfo.GoodsId == 0 {
		return "商品为空"
	}
	//计算购物车商品数量
	var total int
	goodsRepo.DB.Where("user_id = ? and is_deleted = 0", userId).Count(&total)
	if cartRequest.GoodsCount < 1 {
		return "商品数量不能小于 1 ！"
	}
	if cartRequest.GoodsCount > 5 {
		return "超出单个商品的最大购买数量！"
	}
	if total > 20 {
		return "超出购物车最大容量！"
	}

	//将购物车数据保存到数据库
	insertCart := model.ShoppingCart{
		UserId:     uint(userId),
		GoodsId:    cartRequest.GoodsId,
		GoodsCount: cartRequest.GoodsCount,
	}
	if err := receiver.DB.Create(&insertCart).Error; err != nil {
		return "添加失败"
	}
	return "Success"
}

func (receiver ShoppingCartRepo) UpdateNewBeeMallCartItem(cartRequest dto.CartRequest, userId int) string {
	//根据用户id和商品id查询购物车数据
	var temp model.ShoppingCart
	receiver.DB.Where("cart_item_id = ? and is_deleted = 0", cartRequest.CartItemId).First(&temp)
	if temp.CartItemId == 0 {
		return "未查询到记录！"
	}
	//安全性校验
	if uint(userId) != temp.UserId {
		panic("非法操作！")
	}
	if cartRequest.GoodsCount > 5 {
		return "超出单个商品的最大购买数量！"
	}
	//数值相同，不执行数据操作
	if cartRequest.GoodsCount == temp.GoodsCount {
		return "Success"
	}

	temp.GoodsCount = cartRequest.GoodsCount
	temp.UpdateTime = model.Time(time.Now())
	//将购物车数据保存到数据库
	if err := receiver.DB.Model(&temp).Update(&temp).Error; err != nil {
		return "更新失败"
	}
	return "Success"
}

func (receiver ShoppingCartRepo) getNewBeeMallShoppingCartItemVOS(newBeeMallShoppingCartItems []model.ShoppingCart) []vo.NewBeeMallShoppingCartItemVO {
	goodsRepo := NewMallGoodsRepo()
	var newBeeMallShoppingCartItemVOS []vo.NewBeeMallShoppingCartItemVO
	if len(newBeeMallShoppingCartItems) != 0 {
		//封装goodsId切片
		var newBeeMallGoodsIds []int
		for _, item := range newBeeMallShoppingCartItems {
			newBeeMallGoodsIds = append(newBeeMallGoodsIds, item.GoodsId)
		}

		//根据商品id集合查询商品数据
		strGoodsIds := util.Convert(newBeeMallGoodsIds)
		var newBeeMallGoods []model.GoodsInfo
		goodsRepo.DB.Debug().Where("goods_id in (" + strGoodsIds + ")").Order("field(goods_id," + strGoodsIds + ")").Find(&newBeeMallGoods)
		newBeeMallGoodsMap := make(map[int]model.GoodsInfo)
		if len(newBeeMallGoods) != 0 {
			for _, good := range newBeeMallGoods {
				newBeeMallGoodsMap[good.GoodsId] = good
			}
		}

		//处理过长字符串并转换
		for _, item := range newBeeMallShoppingCartItems {
			newBeeMallShoppingCartItemVO := vo.NewBeeMallShoppingCartItemVO{
				CartItemId: item.CartItemId,
				GoodsId:    item.GoodsId,
				GoodsCount: item.GoodsCount,
			}
			if newBeeMallGoodsTemp, ok := newBeeMallGoodsMap[item.GoodsId]; ok {
				newBeeMallShoppingCartItemVO.GoodsCoverImg = newBeeMallGoodsTemp.GoodsCoverImg
				goodsName := newBeeMallGoodsTemp.GoodsName
				//处理字符串
				if len(goodsName) > 28 {
					goodsName = goodsName[:28] + "..."
				}
				newBeeMallShoppingCartItemVO.GoodsName = goodsName
				newBeeMallShoppingCartItemVO.SellingPrice = newBeeMallGoodsTemp.SellingPrice
				newBeeMallShoppingCartItemVOS = append(newBeeMallShoppingCartItemVOS, newBeeMallShoppingCartItemVO)
			}
		}
		return newBeeMallShoppingCartItemVOS
	}
	return nil
}

//查询购物车数据
func (receiver ShoppingCartRepo) findMyNewBeeMallCartItems(cartDTO dto.ShopCartPageDTO) []model.ShoppingCart {

	var newBeeMallShoppingCartItems []model.ShoppingCart
	//这里start应该不会为null
	receiver.DB.Where("user_id = ? and is_deleted = 0", cartDTO.UserId).Limit(cartDTO.Limit).Offset(cartDTO.Start).Find(&newBeeMallShoppingCartItems)
	return newBeeMallShoppingCartItems

}
